package com.example.demo.Controller;

import com.example.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@RequestMapping("/test")//路由注册
//@ResponseBody //默认返回的是页面，这个注解就是将页面变为数据返回
//@Controller //让框架启动的时候加载类（只有加载得类，别人才能访问）
@RestController  //@RestController =@Controller+@ResponseBody
@Slf4j
public class testController {

//    @RequestMapping("/hi")
//     @RequestMapping(value = "/hi",method = RequestMethod.POST)
//    @PostMapping("/hi")
    @GetMapping("/hi")
    public String hello( String name ,Integer age)
    {
        return "Hi: "+name+"age:"+age;
    }


    @GetMapping("/user")
    public String getuser(User user)
    {
        return user.toString();
    }

    @PostMapping("/show-user")
    public String showUser(User user) {
        return user.toString();
    }


    // 接收 JSON 对象（和第三方系统通讯时常见的场景）
    @PostMapping("/show-json-user")
    public String showJSONUser(@RequestBody User user) {
        return user.toString();
    }


    @GetMapping("/show-time")
//    public String showTime(String t, String t2) {
    public String showTime(@RequestParam(value = "t", required = false) String startTime,
                           @RequestParam("t2") String endTime) {
        // startTime/entTime...
        return "开始时间：" + startTime + " | 结束时间：" + endTime;
    }

    @RequestMapping("/show/{name}/{password}")
    public String Login(@PathVariable("name") String name,@PathVariable("password") String password) {
        return name+":"+password;
    }

    @RequestMapping("/upfile")
    public String upfile(@RequestPart("myfile") MultipartFile file) throws IOException {
        String path = "D:\\Generate\\img.png";
        // 保存文件
        file.transferTo(new File(path));
        return path;
    }

    @RequestMapping("/myupfile")
    public String myUpFile(@RequestPart("myfile") MultipartFile file) throws IOException {
        // 根目录
        String path = "D:\\Generate\\";
        // 根目录 + 【唯一的文件名】
        path += UUID.randomUUID().toString().replace("-", "");
        // 根目录 + 唯一的明文件 + 【文件的后缀】  ex:.png
        path += file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //
        file.transferTo(new File(path));
        return path;
    }

    //Spring MVC内置了HttpServletResponse 和 HttpServletRequest
    @RequestMapping("/http")
    public String https(HttpServletResponse response, HttpServletRequest request)
    {
        return request.getParameter("name");
    }

    @RequestMapping("/https")
    public String httpss(HttpServletResponse response, HttpServletRequest request)
    {
        Cookie[] cookies=request.getCookies();
        for(Cookie item:cookies)
        {
            log.error(item.getName()+":"+item.getValue());
        }
        return "get cookies";
    }

    @RequestMapping("/cookie")
    public String cookie(@CookieValue("lisi") String bite) {
        return "cookie：" + bite;
    }


    @RequestMapping("/getua")
    public String getUA(@RequestHeader("user-Agent") String userAgent)
    {
        return userAgent;
    }


    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request)
    {
        HttpSession session=request.getSession(true);
        session.setAttribute("username","userSession1");
        return "创建成功";
    }

    //读取Session方式一
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request)
    {
        HttpSession session=request.getSession(false);
        if(session!=null && session.getAttribute("username")!=null)
        {
            return (String) session.getAttribute("username");
        }
        else
        {
            return "暂无Session信息";
        }
    }
    //读取Session方式二
    @RequestMapping("/getSession1")
    public String getSession1(@SessionAttribute(value = "username",required = false) String username)
    {
        return username;
    }

    @RequestMapping("/respjson")
    public HashMap<String, String> respJson() {
        HashMap<String, String> map = new HashMap<>();
        map.put("Java", "Java Value");
        map.put("MySQL", "MySQL Value");
        map.put("Redis", "Redis Value");
        return map;
    }
}
